'use strict';

/* eslint-disable */
$(function () {
  // var indicators = $('#indicators');
  // for (let i = 0, len = 3; i < len; i++ ) {
  //   var init = $('<li data-target="#carousel-example-generic"></li>');
  //   if (i === 0) {
  //     init.attr('data-slide-to', i).addClass('active');
  //   } else {
  //     init.attr("data-slide-to", i);
  //   }
  //   // init.attr("data-slide-to", i).addClass("active");
  //   indicators.append(init);
  // }
  function monthFilter(time) {
    if (!time) {
      return "";
    }
    const month = [
      "Jan.",
      "Feb.",
      "Mar.",
      "Apr.",
      "May",
      "June",
      "July",
      "Aug.",
      "Sept.",
      "Oct.",
      "Nov.",
      "Dec.",
    ];
    const monthStr = time.split("-")[1];
    const num = Number(monthStr);
    return month[num - 1];
  }
  function dayFilter(time) {
    if (!time) {
      return "";
    }
    return time.split("-")[2];
  }
  function timeEnFilter(time) {
    if (!time) {
      return "";
    }
    const month = [
      "Jan.",
      "Feb.",
      "Mar.",
      "Apr.",
      "May",
      "June",
      "July",
      "Aug.",
      "Sept.",
      "Oct.",
      "Nov.",
      "Dec.",
    ];
    const timeStr = time.split("-");
    const yearStr = timeStr[0];
    const monthStr = timeStr[1];
    const dayStr = timeStr[2];
    const num = Number(monthStr);
    return `${dayStr} ${month[num - 1]} ${yearStr}`;
  }
  function typeMapper(type) {
    switch (type) {
      case "1":
        return "RESEARCH NEWS";
      case "2":
        return "DAILY";
      default:
        return "RESEARCH NEWS";
    }
  };
  function getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
      return decodeURIComponent(r[2]);
    }
    return null;
  }
  function  addParama (key, val) {
    var search = window.location.search;
    var url = '';
    if (search.indexOf('?') != -1) {
        search = search.substring(1);
        var search_arr = search.split('&');
        var url_arr = [];
        var exists = 0;
        for (var i = 0; i < search_arr.length; i++) {
            if (!search_arr[i])
                continue;
            var temp = search_arr[i].split('=');
            if (key == temp[0]) {
                exists = 1;
                url_arr.push(key + '=' + val);
            } else {
                if (temp[0] != 'page' && temp[0] != 'token') {
                    url_arr.push(search_arr[i]);
                }
            }
        }
        if (!exists)
            url_arr.push(key + '=' + val);
        url = window.location.pathname + '?' + url_arr.join('&');
    } else {
        url = window.location.pathname + '?' + key + '=' + val;
    }
    window.location.href = url;
  };

  var page = getQueryString("page");
  var id = getQueryString("id");
  if(id) {
    // 详情页
    $("#newsListWrapper").empty();
    $("#newsSearch").hide();
    $("#newsArchives").hide();
    var req = $.ajax({
      url: "http://39.106.171.39:8011/mbl/News/getNewsItem",
      method: "GET",
      data: {
        newsid: id,
      },
      dataType: "json",
    });
    req.done(function (data) {
      $("#newsOthers").show();
      $("#newsTypeTip").text(typeMapper(data.newstype));
      $("#newsDateTip").text(data.newsdate);
      var h1 = $(
        '<h1 class="news-detail__title">{{ pageData.eventtitle }}</h1>'
      );
      h1.text(data.newstitle);
      $("#newsListWrapper").append(h1).append(data.newstext);
    })
    
    return;
  }
  if (!page) {
    page = 1;
  }
  var requestFactory = function (page) {
    return $.ajax({
      url: "http://39.106.171.39:8011/mbl/News/getNewsList",
      method: "GET",
      data: {
        page: page || 1,
        pagesize: 7,
      },
      dataType: "json",
    });
  };
  var request = requestFactory(page);

  function handlerInit(data, status) {
    console.log("status:", status);
    console.log("data:", data);
    var newslist = data.rows;
    var pages = data.pageCount;
    // 置顶新闻
    const temp = newslist || [];
    let i = 0;
    let topInfo = null;
    for (; i < temp.length; i++) {
      if (temp[i].topflag === "1") {
        topInfo = temp[i];
        break;
      }
    }
    var topInfoImg = $("#topInfoImg");
    topInfoImg.attr("src", topInfo.picture || "../public/img/subject_1.png");
    var topInfoTitle = $("#topInfoTitle");
    topInfoTitle.text(topInfo.newstitle);
    // 新闻列表
    var navigation = $("#navigation");
    // 如果新闻列表已经存在则删除
    $("section.border-bottom-line").remove();

    for (let i = 0; i < newslist.length; i++) {
      var item = $('<section class="new border-bottom-line pointer"></section>');
      var divElem = $('<div class="desc"></div>');
      var h3 = $("<h3></h3>").text(newslist[i].newstitle);
      var p = $('<p class="type"></p>').text(typeMapper(newslist[i].newstype));
      var span = $("<span></span>").text(timeEnFilter(newslist[i].newsdate));
      var img = $("<img>").attr(
        "src",
        newslist[i].picture || "../public/img/image_demo.png"
      );

      divElem.append(p).append(h3).append(span);
      item.append(divElem).append(img);

      item.click(function () {
        addParama("id", newslist[i].newsid);
        // window.location.href =
        //   window.location.pathname + "?id=" + newslist[i].newsid;
      })

      item.insertBefore(navigation);
    }
    // 分页列表
    for (let i = 0, len = pages; i < len; i++ ) {
      var num = i + 1;
      var item = $("<li></li>");
      var aElem = $('<a href=""></a>').text(num);
      item.append(aElem);
      aElem.click(function (e) {
        e.preventDefault()
        window.location.href = window.location.pathname + "?page=" + num;
      });
      item.insertBefore($("#next"));
    }
  }
  request.done(handlerInit);
  request.fail(function (jqXHR, textStatus) {
    alert("Request failed: " + textStatus);
  });
  // 分页
  var prev = $("#prev");
  prev.click(function () {
    // 获取路径参数
    var page = getQueryString("page");
    if (page && Number(page) > 1) {
      page = Number(page) - 1;
      addParama("page", page);
      // window.location.href = window.location.pathname + "?page=" + page;
    } else {
      return;
    }
  });
  var next = $("#next");
  next.click(function () {
    // 获取路径参数
    var page = getQueryString("page");
    if (page) {
      page = Number(page) + 1;
      // window.location.href = window.location.pathname + "?page="+page;
      addParama("page", page);
    } else {
      addParama("page", 2);
      // window.location.href = window.location.pathname + "?page=2";
    }
  });
});
